package cn.lili.modules.goods.entity.vos;

import cn.hutool.core.date.DateUtil;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.modules.file.util.FileUtil;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsStatusEnum;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.system.entity.dto.GoodsSetting;
import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Data;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Data
public class ImportResult {

	private String goodsNo;

	private String state;

	private String errorCause;

	/**
	 * 初始化Goods,校验产品编号
	 */
	public Goods getGoods(GoodsSpuImportVo goodsSpuImportVo) {
		Goods goods = new Goods();
		String goodsNo = goodsSpuImportVo.getGoodsNo();
		if (StringUtils.isBlank(goodsNo)) {
			this.setGoodsNo("未知产品");
			this.setState("导入失败");
			this.setErrorCause("产品编号错误");
			return null;
		}
		this.setGoodsNo(goodsNo);
		return checkCategory(goodsSpuImportVo, goods);
	}

	/**
	 * 校验商品分类
	 */
	private Goods checkCategory(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String category = goodsSpuImportVo.getCategory();
		if (StringUtils.isBlank(category)) {
			this.setState("导入失败");
			this.setErrorCause("商品分类错误");
			return null;
		}
		String[] getCategoryArr = category.split("-");
		if (getCategoryArr.length != 3) {
			this.setState("导入失败");
			this.setErrorCause("商品分类错误");
			return null;
		}
		String firstCategory = goodsSpuImportVo.getCategoryMap().get(getCategoryArr[0]);
		String secondCategory = goodsSpuImportVo.getCategoryMap().get(getCategoryArr[1]);
		String thirdCategory = goodsSpuImportVo.getCategoryMap().get(getCategoryArr[2]);
		if (StringUtils.isBlank(firstCategory) || StringUtils.isBlank(secondCategory)
				|| StringUtils.isBlank(thirdCategory)) {
			this.setState("导入失败");
			this.setErrorCause("商品分类错误");
			return null;
		}
		goods.setCategoryPath(String.join(",", firstCategory, secondCategory, thirdCategory));
		return checkGoodsType(goodsSpuImportVo, goods);
	}

	/**
	 * 校验商品类型
	 */
	private Goods checkGoodsType(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String goodsType = goodsSpuImportVo.getGoodsType();
		if (StringUtils.isBlank(goodsType)) {
			this.setState("导入失败");
			this.setErrorCause("商品类型错误");
			return null;
		}
		goods.setGoodsType(goodsType);
		return checkGoodsName(goodsSpuImportVo, goods);
	}

	/**
	 * 校验商品名称
	 */
	private Goods checkGoodsName(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String goodsName = goodsSpuImportVo.getGoodsName();
		if (StringUtils.isBlank(goodsName)) {
			this.setState("导入失败");
			this.setErrorCause("商品名称错误");
			return null;
		}
		goods.setGoodsName(goodsName);
		return checkSellingPoint(goodsSpuImportVo, goods);
	}

	/**
	 * 校验卖点
	 */
	private Goods checkSellingPoint(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String sellingPoint = goodsSpuImportVo.getSellingPoint();
		if (StringUtils.isBlank(sellingPoint)) {
			this.setState("导入失败");
			this.setErrorCause("卖点错误");
			return null;
		}
		goods.setSellingPoint(sellingPoint);
		return checkGoodsUnit(goodsSpuImportVo, goods);
	}

	/**
	 * 校验计量单位
	 */
	private Goods checkGoodsUnit(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String goodsUnit = goodsSpuImportVo.getGoodsUnit();
		if (StringUtils.isBlank(goodsUnit)) {
			this.setState("导入失败");
			this.setErrorCause("计量单位错误");
			return null;
		}
		goods.setGoodsUnit(goodsUnit);
		return checkSalesArea(goodsSpuImportVo, goods);
	}

	/**
	 * 校验销售区域
	 */
	private Goods checkSalesArea(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String salesArea = goodsSpuImportVo.getSalesArea();
		Store store = goodsSpuImportVo.getStore();
		if ("全国销售".equals(salesArea)) {
			goods.setStoreAddressIdPath("");
			goods.setStoreAddressPath("");
		} else if ("区域销售".equals(salesArea)) {
			goods.setStoreAddressPath(store.getStoreAddressPath());
			goods.setStoreAddressIdPath(store.getStoreAddressIdPath());
		} else {
			this.setState("导入失败");
			this.setErrorCause("销售区域错误");
			return null;
		}
		return checkGoodsGallery(goodsSpuImportVo, goods);
	}

	/**
	 * 校验商品图片 商品图片后缀
	 */
	private Goods checkGoodsGallery(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String goodsGallery = goodsSpuImportVo.getGoodsGallery();
		String goodsGallerySuffix = goodsSpuImportVo.getGoodsGallerySuffix();
		Map<String, String> goodsImgDictMap = goodsSpuImportVo.getGoodsImgDictMap();
		List<String> goodsGalleryList = goodsSpuImportVo.getGoodsGalleryList();
		if (goodsGalleryList == null) {
			goodsGalleryList = new ArrayList<>();
			goodsSpuImportVo.setGoodsGalleryList(goodsGalleryList);
		}

		if (StringUtils.isBlank(goodsGallery) || StringUtils.isBlank(goodsGallerySuffix)) {
			this.setState("导入失败");
			this.setErrorCause("商品图片错误");
			return null;
		}
		String[] goodsGalleryArr = goodsGallery.split(";");
		String goodsUrl = goodsImgDictMap.get(goodsGalleryArr[0] + "." + goodsGallerySuffix);
		if (StringUtils.isBlank(goodsUrl)) {
			this.setState("导入失败");
			this.setErrorCause("商品图片错误");
			return null;
		}
		for (String url : goodsGalleryArr) {
			String s = goodsImgDictMap.get(url + "." + goodsGallerySuffix);
			if (StringUtils.isNotBlank(s)) {
				goodsGalleryList.add(s);
			}
		}
		GoodsSetting goodsSetting = goodsSpuImportVo.getGoodsSetting();

		// 缩略图
		String thumbnail = FileUtil.getUrl(goodsUrl, goodsSetting.getAbbreviationPictureWidth(),
				goodsSetting.getAbbreviationPictureHeight());

		// 小图
		String small = FileUtil.getUrl(goodsUrl, goodsSetting.getSmallPictureWidth(),
				goodsSetting.getSmallPictureHeight());

		goods.setOriginal(goodsUrl);
		goods.setSmall(small);
		goods.setThumbnail(thumbnail);

		return checkIntro(goodsSpuImportVo, goods);
	}

	/**
	 * 校验商品描述 商品详情图片 商品详情图片后缀
	 */
	private Goods checkIntro(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String goodsDescribe = goodsSpuImportVo.getGoodsDescribe();
		String intro = goodsSpuImportVo.getIntro();
		String introSuffix = goodsSpuImportVo.getIntroSuffix();
		if (StringUtils.isBlank(goodsDescribe) || StringUtils.isBlank(intro) || StringUtils.isBlank(introSuffix)) {
			this.setState("导入失败");
			this.setErrorCause("商品详情错误");
			return null;
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<p>").append(goodsDescribe);
		String[] introArr = intro.split(";");
		Map<String, String> goodsImgDictMap = goodsSpuImportVo.getGoodsImgDictMap();
		for (String introImg : introArr) {
			String imgDict = goodsImgDictMap.get(introImg + "." + introSuffix);
			if (StringUtils.isBlank(imgDict)) {
				this.setState("导入失败");
				this.setErrorCause("商品详情错误");
				return null;
			}
			stringBuilder.append("<img src=\"").append(imgDict).append("\" style=\"max-width:100%\" />");
		}
		stringBuilder.append("</p>");
		String introStr = stringBuilder.toString();

		goods.setIntro(introStr);
		return checkRelease(goodsSpuImportVo, goods);
	}

	/**
	 * 校验是否立即发布
	 */
	private Goods checkRelease(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String release = goodsSpuImportVo.getRelease();
		if (release == null) {
			this.setState("导入失败");
			this.setErrorCause("是否立即发布错误");
			return null;
		}
		if ("true".equals(release)) {
			goods.setMarketEnable(GoodsStatusEnum.UPPER.name());
		} else {
			goods.setMarketEnable(GoodsStatusEnum.DOWN.name());
		}
		return checkShelfLife(goodsSpuImportVo, goods);
	}

	/**
	 * 校验保质期
	 */
	private Goods checkShelfLife(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String shelfLife = goodsSpuImportVo.getShelfLife();
		if (shelfLife == null) {
			this.setState("导入失败");
			this.setErrorCause("保质期错误");
			return null;
		}
		goods.setShelfLife(shelfLife);
		return checkProductionDate(goodsSpuImportVo, goods);
	}

	/**
	 * 校验生产日期
	 */
	private Goods checkProductionDate(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		String productionDate = goodsSpuImportVo.getProductionDate();
		if (productionDate == null) {
			this.setState("导入失败");
			this.setErrorCause("生产日期错误");
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = DateUtil.parse(productionDate);
		String format = sdf.format(date);
		goods.setProductionDate(format);
		return init(goodsSpuImportVo, goods);
	}

	/**
	 * 添加初始数据
	 */
	private Goods init(GoodsSpuImportVo goodsSpuImportVo, Goods goods) {
		GoodsSetting goodsSetting = goodsSpuImportVo.getGoodsSetting();
		Store store = goodsSpuImportVo.getStore();
		// 评论次数
		goods.setCommentNum(0);
		// 购买次数
		goods.setBuyCount(0);
		// 商品评分
		goods.setGrade(100.0);
		// 审核状态
		goods.setAuthFlag(Boolean.TRUE.equals(goodsSetting.getGoodsCheck())
				? GoodsAuthEnum.TOBEAUDITED.name()
				: GoodsAuthEnum.PASS.name());
		// 是否自营
		goods.setSelfOperated(store.getSelfOperated() == 1 ? true : false);
		// 店铺ID
		goods.setStoreId(store.getId());
		// 店铺名称
		goods.setStoreName(store.getStoreName());
		// 是否为推荐商品
		goods.setRecommend(false);
		// 销售模式
		goods.setSalesModel("RETAIL");
		goods.setBrandId("0");
		return goods;
	}

	/**
	 * 初始化GoodsSku
	 */
	public GoodsSku getGoodsSku(GoodsSkuImportVo goodsSkuImportVo) {
		GoodsSku goodsSku = new GoodsSku();
		return checkGoodsSkuName(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验产品名称
	 */
	private GoodsSku checkGoodsSkuName(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		String goodsName = goodsSkuImportVo.getGoodsName();
		if (StringUtils.isBlank(goodsName)) {
			this.setState("导入失败");
			this.setErrorCause("商品名称错误");
			return null;
		}
		goodsSku.setGoodsName(goodsName);
		return checkSpecs(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验规格名 图片 图片后缀
	 */
	private GoodsSku checkSpecs(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		Map<String, String> goodsImgDictMap = goodsSkuImportVo.getGoodsImgDictMap();
		String specs = goodsSkuImportVo.getSpecs();
		String specsImg = goodsSkuImportVo.getSpecsImg();
		String specsImgSuffix = goodsSkuImportVo.getSpecsImgSuffix();
		if (StringUtils.isBlank(specs) || StringUtils.isBlank(specsImg) || StringUtils.isBlank(specsImgSuffix)) {
			this.setState("导入失败");
			this.setErrorCause("规格信息错误");
			return null;
		}
		Map<String, Object> specsMap = new HashMap<>();
		specsMap.put("规格", specs);
		List<GoodsSkuSpecsImages> specsImagesList = new ArrayList<>();
		String[] specsImgArr = specsImg.split(";");
		for (String specsImgStr : specsImgArr) {
			String name = specsImgStr + "." + specsImgSuffix;
			String url = goodsImgDictMap.get(name);
			GoodsSkuSpecsImages goodsSkuSpecsImages = new GoodsSkuSpecsImages();
			goodsSkuSpecsImages.setName(name);
			goodsSkuSpecsImages.setUrl(url);
			goodsSkuSpecsImages.setStatus("finished");
			specsImagesList.add(goodsSkuSpecsImages);
		}
		specsMap.put("images", specsImagesList);
		goodsSku.setSpecs(JSON.toJSONString(specsMap));

		return checkWeight(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验重量
	 */
	private GoodsSku checkWeight(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		String weight = goodsSkuImportVo.getWeight();
		if (StringUtils.isBlank(weight)) {
			this.setState("导入失败");
			this.setErrorCause("重量错误");
			return null;
		}
		goodsSku.setWeight(Double.parseDouble(weight));
		return checkSn(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验货号
	 */
	private GoodsSku checkSn(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		String sn = goodsSkuImportVo.getSn();
		if (StringUtils.isBlank(sn)) {
			this.setState("导入失败");
			this.setErrorCause("货号错误");
			return null;
		}
		goodsSku.setSn(sn);
		return checkQuantity(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验库存
	 */
	private GoodsSku checkQuantity(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		String quantity = goodsSkuImportVo.getQuantity();
		if (StringUtils.isBlank(quantity)) {
			this.setState("导入失败");
			this.setErrorCause("库存错误");
			return null;
		}
		goodsSku.setQuantity(Integer.parseInt(quantity));
		return checkCost(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验成本价
	 */
	private GoodsSku checkCost(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		String cost = goodsSkuImportVo.getCost();
		if (StringUtils.isBlank(cost)) {
			this.setState("导入失败");
			this.setErrorCause("成本价错误");
			return null;
		}
		goodsSku.setCost(Double.parseDouble(cost));
		return checkPrice(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 校验价格
	 */
	private GoodsSku checkPrice(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		String price = goodsSkuImportVo.getPrice();
		if (StringUtils.isBlank(price)) {
			this.setState("导入失败");
			this.setErrorCause("重量错误");
			return null;
		}
		goodsSku.setPrice(Double.parseDouble(price));
		return init(goodsSkuImportVo, goodsSku);
	}

	/**
	 * 添加初始数据
	 */
	private GoodsSku init(GoodsSkuImportVo goodsSkuImportVo, GoodsSku goodsSku) {
		Goods goods = goodsSkuImportVo.getGoods();
		// 购买数量
		goodsSku.setBuyCount(0);
		// 评价数量
		goodsSku.setCommentNum(0);
		// 商品ID
		goodsSku.setGoodsId(goods.getId());
		// 计量单位
		goodsSku.setGoodsUnit(goods.getGoodsUnit());
		// 商品好评率
		goodsSku.setGrade(100.0);
		// 审核状态
		goodsSku.setAuthFlag(goods.getAuthFlag());
		// 上架状态
		goodsSku.setMarketEnable(goods.getMarketEnable());
		// 原图路径
		goodsSku.setOriginal(goods.getOriginal());
		// 是否自营
		goodsSku.setSelfOperated(goods.getSelfOperated());
		// 店铺ID
		goodsSku.setStoreId(goods.getStoreId());
		// 店铺名称
		goodsSku.setStoreName(goods.getStoreName());
		// 卖点
		goodsSku.setSellingPoint(goods.getSellingPoint());
		// 小图路径
		goodsSku.setSmall(goods.getSmall());
		// 缩略图路径
		goodsSku.setThumbnail(goods.getThumbnail());
		// 浏览数量
		goodsSku.setViewCount(0);
		// 规格信息
		goodsSku.setSimpleSpecs("规格");
		// 是否为推荐商品
		goodsSku.setRecommend(false);
		goodsSku.setSalesModel(goods.getSalesModel());
		goodsSku.setBrandId(goods.getBrandId());
		goodsSku.setCategoryPath(goods.getCategoryPath());
		goodsSku.setIntro(goods.getIntro());
		goodsSku.setSalesModel(goods.getSalesModel());
		// 提现折扣率
		goodsSku.setFee(CurrencyUtil.div(goodsSku.getCost(), goodsSku.getPrice()));
		return goodsSku;
	}

}
